package com.offcn.gateway.filter;


import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

@Configuration
public class AuthorizationFilter implements GlobalFilter, Ordered {

    // 引入公钥
    private static final String PUBLIC_KEY = "public.key";

    /**
     * 读取公钥的数据
     */
    private String getPublicKey(){
        ClassPathResource resource = new ClassPathResource(PUBLIC_KEY);
        try (
                BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(resource.getInputStream())
                );
        ){
            String publicKey = bufferedReader.readLine();
            return publicKey;
        } catch(IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 全局过滤器的主要方法
     * @param exchange  用来获取 请求对象 和 响应对象
     * @param chain   用于实现放行操作: return chain.filter(exchange);
     *                拦截操作： 响应对象.setComplete();  建议在拦截之前，设定响应状态码
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求对象 和 响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 如果当前操作是 用户登录，用户注册，用户获取验证码 放行，不进行拦截
        String path = request.getURI().getPath();
        if (path.startsWith("/api/user/login")||path.startsWith("/api/userOauth/login") || path.startsWith("/api/user/add") || path.startsWith("/api/user/sendCode")|| path.startsWith("/api/page")|| path.startsWith("/api/search")|| path.startsWith("/api/goods")){
            // 放行
            return chain.filter(exchange);
        }
        // 获取 令牌  （从三个方向获取 请求头，请求参数，Cookie）
        // 从请求头中获取令牌
        String token = request.getHeaders().getFirst("Authorization");
        boolean headerHasToken = true;

        // 如果请求头中没有，从请求参数中获取
        if (token == null) {
            token = request.getQueryParams().getFirst("Authorization");
            headerHasToken = false;
        }
        // 如果请求头和请求参数中都没有，从cookie中获取
        if (token == null) {
            HttpCookie cookie = request.getCookies().getFirst("Authorization");
            if (cookie != null) {
                token = cookie.getValue();
                headerHasToken = false;
            }
        }

        // 以上三个位置都没有 ，则拦截
        if (StringUtils.isEmpty(token)) {
            //response.setStatusCode(HttpStatus.UNAUTHORIZED); //401
//            return response.setComplete(); // 拦截
            // 跳转到登录界面
           // response.setStatusCode(HttpStatus.SEE_OTHER); // 303
           // response.getHeaders().set("Location","http://localhost:10000/oauth/login?from=" + path);
            HttpHeaders headers = response.getHeaders();
            //设置响应头内容Content-Type 响应内容类型
            headers.add("Content-Type","application/json; charset=UTF-8");
            //禁止缓存
            headers.add("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
            //设置响应内容
            String body="{\"code\":30003,\"flag\":false,\"data\":null,\"msg\":\"请登录\"}";
            return response.writeWith(Mono.just(response.bufferFactory().wrap(body.getBytes())));


           // return response.setComplete();
        }

        // 需要在每个微服务内部实现令牌校验，网关校验不需要了
        String realToken=token.replace("bearer ","").replace("Bearer ","");
        // 检验当前令牌是否有效
        try {
            Jwt jwt = JwtHelper.decodeAndVerify(realToken, new RsaVerifier(getPublicKey()));
            // 判断 令牌中是否有 Bearer
            if (!token.startsWith("Bearer ")) {
                token = "Bearer " + token;
            }

            // 判断请求头中是否有令牌，如果没有 ，加入到请求头中，在微服务内部获取令牌直接从请求头中获取

            request.mutate().header("Authorization",token);
            return chain.filter(exchange);
        } catch (Exception e) {
            e.printStackTrace();

            //解析令牌失败，返回json
            HttpHeaders headers = response.getHeaders();
            //设置响应头内容Content-Type 响应内容类型
            headers.add("Content-Type","application/json; charset=UTF-8");
            //禁止缓存
            headers.add("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
            //设置响应内容
            String body="{\"code\":50005,\"flag\":false,\"data\":null,\"msg\":\"token已经失效\"}";
            return response.writeWith(Mono.just(response.bufferFactory().wrap(body.getBytes())));

        }





    }



    /**
     * Ordered的方法，为当前过滤器设定启动顺序，返回值越低，越优先执行
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
